<?php
/**
 * Created by PhpStorm.
 * User: xiangfeng
 * Date: 2022/4/9
 * Time: 10:05 AM
 */

namespace app\api\service;


use app\api\http\exceptions\ApiErr;
use app\api\http\exceptions\ApiExceptions;
use app\api\model\SerCardInfoModel;
use app\api\model\UserModel;
use think\Service;

class UserService extends Service
{
    private static $field = 'id as user_id,college_name,college_dep_name,college_major_name,uname, phone,certification_status,introduce,nickname,avatar,openid,birthday,join_year,join_type,working_unit,email,image_list';

    /**
     * 查询基本信息
     * @param int $user_id
     * @param string $field
     * @return array
     * @throws ApiExceptions
     */
    public static function get(int $user_id, $field = ''): array
    {
        $field = empty($field) ? self::$field : $field;
        $map = ['id' => $user_id, 'status' => 0];
        $user = UserModel::mk()->where($map)->field($field)->findOrEmpty();
        if ($user->isEmpty()) throw new ApiExceptions(ApiErr::USER_INFO_NO_EXIST);
        return $user->hidden(['create_time', 'delete_time', 'update_time'])->toArray();
    }

    /**
     * 根据手机号查询Uid
     * @param string $phone
     * @return int
     * @throws ApiExceptions
     */
    public static function getUidByPhone(string $phone): int
    {
        $map = ['phone' => $phone];
        $user = UserModel::mk()->where($map)->field('id')->findOrEmpty();;
        if ($user->isEmpty()) throw new ApiExceptions(ApiErr::USER_LOGIN_ERROR);
        return (int)$user['id'];
    }

    /**
     * 检查用户是否存在
     * @param int $user_id
     * @return bool
     */
    public static function checkUserIsExist(int $user_id): bool
    {
        $info = UserModel::mk()->field('id')->where(['id' => $user_id])->count();
        return !empty($info) ? true : false;
    }

    /**
     * 检查用户是否注册
     * @param int $user_id
     * @return bool
     */
    public static function checkUserIsReg(int $user_id): bool
    {
        $info = UserModel::mk()->field('is_reg')->where(['id' => $user_id, 'is_reg' => 1])->count();
        return !empty($info) ? true : false;
    }

    /**
     * 检查是否认证
     * @param int $user_id
     * @return bool
     */
    public static function checkUserIsCertification(int $user_id): bool
    {
        $map = ['id' => $user_id, 'status' => 0, 'certification_status' => 1];
        $user = UserModel::mk()->where($map)->field('id')->count();
        return !empty($user) ? true : false;
    }

    /**
     * 查询服务卡权益
     * @param int $user_id
     * @param string $field
     * @param int $limit
     * @param int $tag
     * @return array
     * @throws ApiExceptions
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getSerCardList(int $user_id, string $field = 'id,title,cover_image,content', int $limit = 10, int $tag = 0): array
    {
        $map = ['status' => 1];
        if ($tag == 1) {
            $info = SerCardInfoModel::mk()->where($map)->field($field)->order('sorts desc')->column('title');
        } else {
            $info = SerCardInfoModel::mk()->where($map)->field($field)->order('sorts desc')->limit($limit)->selectOrFail();
            if ($info->isEmpty()) throw new ApiExceptions(ApiErr::SELECT_DB_FAILED);
            $info = $info->toArray();
        }
        return $info;
    }

    /**
     * 查询我的校友卡
     * @param int $user_id
     * @return array
     * @throws ApiExceptions
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getUserCardInfo(int $user_id)
    {
        $data = self::get($user_id, 'id as user_id,college_name,uname,college_dep_name,college_major_name,join_year,join_type,avatar');
        $card = self::getSerCardList($user_id, 'title', 6, 1);
        $data['ser_card'] = $card;//清桐服务卡权益
        return $data;
    }

    /**
     * 修改
     * @param int $user_id
     * @param array $param
     * @return bool|int
     */
    public static function update(int $user_id, array $param): bool
    {
        return UserModel::mUpdate($param, 'id', ['id' => $user_id]);
    }

    /**
     * 校友通讯录
     * @param int $user_id
     * @param array $page_config
     * @param string $keywords
     * @param int $type
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public static function getColleageUser(int $user_id, array $page_config, string $keywords, int $type)
    {
        $field = 'id as user_id,nickname,uname,college_name,college_dep_name,join_year,avatar,is_reg';
        if ($type == 1) {
            $ids = UserFollowService::getFocusUserIds($user_id);
            if (!empty($keywords)) {
                $where = [
                    ['uname', 'like', '%' . $keywords . '%'],
                    ['id', 'in', $ids],
                    ['status', '=', 0],
                    ['delete_time', '=', 0],
                ];
            } else {
                $where = [
                    ['id', 'in', $ids],
                    ['status', '=', 0],
                    ['delete_time', '=', 0],
                ];
            }
        } else {
            $where = [
                'status' => 0,
                'delete_time' => 0,
            ];
            if (!empty($keywords)) {
                $where = [
                    ['uname', 'like', '%' . $keywords . '%'],
                    ['status', '=', 0],
                    ['delete_time', '=', 0],
                ];
            }
        }

        $data = UserModel::mk()->where($where)->order('id desc')->field($field)->paginate($page_config)->each(function ($item) use ($user_id) {
            $item['is_follow'] = UserFollowService::isFollowFriend($user_id, $item['user_id']);
            return $item;
        });
        return $data;
    }

    /**
     * 查询好友详情
     * @param int $user_id
     * @param $friend_user_id
     * @return array
     * @throws ApiExceptions
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getFriendInfo(int $user_id, $friend_user_id): array
    {
        $is_follow = UserFollowService::isFollowFriend($user_id, $friend_user_id);
        $field = 'id as user_id,college_name,college_dep_name,uname, phone,certification_status,introduce,birthday,join_year,join_type,working_unit,email,image_list';
        $is_Cer = $user_id == $friend_user_id ? true : self::checkUserIsCertification($user_id);
        //未认证且未加好友，无法查看对方电话、邮箱的联系方式。
        $map = ['id' => $friend_user_id, 'status' => 0];
        $friend_user = UserModel::mk()->where($map)->field($field)->findOrEmpty();
        if ($friend_user->isEmpty()) throw new ApiExceptions(ApiErr::USER_FRIEND_NO_EXIST);
        $friend_user['image_list'] = !empty($friend_user['image_list']) ? json_decode($friend_user['image_list'], true) : [];
        $friend_user['is_follow'] = $is_follow;//是否加好友
        $friend_user['phone'] = $is_follow == true && $is_Cer == true ? $friend_user['phone'] : '';
        $friend_user['email'] = $is_follow == true && $is_Cer == true ? $friend_user['email'] : '';
        return $friend_user->hidden(['create_time', 'delete_time', 'update_time'])->toArray();
    }
}